package controllers

import (
	"cat_mouse/core/service"
	"cat_mouse/infra/common"
	"cat_mouse/infra/response"
	infraSvc "cat_mouse/infra/service"
	"cat_mouse/infra/utils"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"strconv"
)

type RoomController struct {
}

func RoomControllerRegister(router *gin.RouterGroup) {
	socketController := RoomController{}
	router.POST("", socketController.CreateRoom)
	router.POST("/:roomId/join", socketController.JoinRoom)
}

func (s *RoomController) CreateRoom(c *gin.Context) {
	//TODO 创建房间
}

func (s *RoomController) JoinRoom(c *gin.Context) {
	var (
		conn   *websocket.Conn
		userId string
		roomId int
		err    error
	)
	if roomId, err = strconv.Atoi(c.Param("roomId")); err != nil {
		response.InputError(c, err.Error())
		return
	}
	userId = utils.MustGetUserId(c)
	if conn, err = common.WsUpGrader.Upgrade(c.Writer, c.Request, nil); err != nil {
		response.InternalError(c, "WebSocket连接失败")
		return
	}

	roomEngine, ok := common.RoomEngines.Load(roomId)
	if !ok {
		response.InternalError(c, "房间信息异常")
		return
	}

	client := infraSvc.NewWsClient(infraSvc.WithConnOpt(conn), infraSvc.WithUserId(userId))
	go client.Write()
	client.Read(roomEngine.(*service.Engine).GetReceiveCh())
}
